package cn.hzking.gjmall.activitys.refund;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Looper;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSStsTokenCredentialProvider;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerActivity;
import cn.hzking.gjmall.R;
import cn.hzking.gjmall.base.ColorStatuBarActivity;
import cn.hzking.gjmall.bean.refund.OssBean;
import cn.hzking.gjmall.bean.refund.OssRandomNameBean;
import cn.hzking.gjmall.net.RetrofitFactory;
import cn.hzking.gjmall.net.base.BaseEntity;
import cn.hzking.gjmall.net.base.BaseObserver;
import cn.hzking.gjmall.utils.ListUtils;
import cn.hzking.gjmall.utils.PictureUtils;
import cn.hzking.gjmall.utils.UIUtils;
import cn.hzking.gjmall.view.SimpleOptionView;
import cn.hzking.gjmall.view.WheelView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;


public class ApplyRefundActivity extends ColorStatuBarActivity {
    @Bind(R.id.simpleTileView) SimpleOptionView titleTv;
    @Bind(R.id.rl_reason) RelativeLayout reasonRl;
    @Bind(R.id.tv_reason) TextView reasonTv;
    @Bind(R.id.iv_one) ImageView oneIv;
    @Bind(R.id.iv_two) ImageView twoIv;
    @Bind(R.id.iv_three) ImageView threeIv;
    @Bind(R.id.iv_four) ImageView fourIv;
    @Bind(R.id.tv_abandon) TextView abandonTv;
    @Bind(R.id.tv_continue) TextView continueTv;
    private static final int REQUEST_CODE_CHOOSE_PHOTO = 1;//选择图片
    private static final int REQUEST_CODE_COMMIT = 5;//提交请求
    private static final int REQUEST_CODE_REFUND = 10;//提交请求
    final public static int REQUEST_READ = 100;//读写内存权限
    private ArrayList<String> mylist;
    private ArrayList<String> piclist;
    private ArrayList<String> textlist;
    private ArrayList<String> lastUpLoad=new ArrayList<>();
    private ArrayList<String> textNames = new ArrayList<>();

    private View popview;
    private PopupWindow popwindow;
    private WheelView wheelView;
    private String lastString;
    private TextView sure;
    private String typeName;
    private int index;
    private  final  int CURRENTINDEXT = 0;
    private ArrayList<String> list;
    private String filePath = null;
    RelativeLayout leftRl;
    RelativeLayout rightRl;

    private int picIndex;
    private int orderId;
    private int orderItemId;
    private String path = null;
    private OSSClient oss;
    public String objectKeyPrefix;
    public String bucket;
    public String expiration;
    private String accessKeyId;
    private String accessKeySecret;
    private String securityToken;
    private boolean hasSTStoken;
    private String[] pics=null;
    private int successPic=0;
    private int reasonId;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_apply_refund);
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        if(getIntent()!=null){
            orderId=getIntent().getIntExtra("orderId",0);
            orderItemId=getIntent().getIntExtra("orderItemId",0);
        }
        init();
    }

    private void init() {
        titleTv.setTitle("售后申请");
        textlist=new ArrayList<>();
        mylist=new ArrayList<>();
        piclist=new ArrayList<>();
        textlist.clear();
        textlist.add("自动退款");
        textlist.add("七天无理由退款");
        textlist.add("质量问题");
        initOnclick();
    }

    private void initOnclick() {
        reasonRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initPop();
            }
        });
        oneIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                picIndex=0;
                select();
            }
        });
        twoIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                picIndex=1;
                select();
            }
        });
        threeIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                picIndex=2;
                select();
            }
        });
        fourIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                picIndex=3;
                select();
            }
        });
        getToken();
        continueTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!TextUtils.isEmpty(reasonTv.getText().toString())){
                    String name=reasonTv.getText().toString().trim();
                    if(name.equals("自动退款")){
                        reasonId=1;
                    }else if(name.equals("七天无理由退款")){
                        reasonId=2;
                    }else if(name.equals("质量问题")){
                        reasonId=3;
                    }else {
                        UIUtils.showToast(ApplyRefundActivity.this, "请选择退款理由", Toast.LENGTH_SHORT);
                        return;
                    }
                    if(!ListUtils.isEmpty(mylist)){
                        if(hasSTStoken){
                            getRandomName(mylist.size());//获取随机文件名
                        }else {
                            UIUtils.showToast(ApplyRefundActivity.this, "提交信息失败", Toast.LENGTH_SHORT);
                        }
                    }else {//不需要传图片
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                commit();
                            }
                        });

                }
                }else {
                    UIUtils.showToast(ApplyRefundActivity.this, "请选择退款理由", Toast.LENGTH_SHORT);
                }
            }
        });
    }

    private void getRandomName(int size) {
        Log.e("---","获取随机文件名");
        RetrofitFactory.getInstant().API()
                .getRandomName(size)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<OssRandomNameBean>(this,false) {
                    @Override
                    protected void onSuccees(OssRandomNameBean ossRandomNameBean) throws Exception {
                        textNames.clear();
                        piclist.clear();
                        textNames.addAll(ossRandomNameBean.getData());
                        for (int i = 0; i <mylist.size(); i++) {
                            int start = mylist.get(i).lastIndexOf(".");
                            String filename = textNames.get(i)+mylist.get(i).substring(start , mylist.get(i).length());
                            piclist.add(filename);
                        }
                        if(!ListUtils.isEmpty(piclist)){
                            lastUpLoad.clear();
                            successPic=0;
                            for (int i = 0; i <piclist.size() ; i++) {
                                compress(i);
                            }
                        }
                    }

                    @Override
                    protected void onFailure(Throwable e, boolean isNetWorkError) throws Exception {
                    }

                    @Override
                    protected void onCodeError(OssRandomNameBean ossRandomNameBean) throws Exception {
                        super.onCodeError(ossRandomNameBean);
                        UIUtils.showToast(ApplyRefundActivity.this, ossRandomNameBean.getErrorMsg(), Toast.LENGTH_SHORT);
                    }
                });
    }


    private void getToken() {
        RetrofitFactory.getInstant().API()
                .getOssToken()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<OssBean>(this,false) {
                    @Override
                    protected void onSuccees(OssBean ossBean) throws Exception {
                        OssBean.DataBean data=ossBean.getData();
                        if(data!=null){
                            accessKeyId = data.getAccessKeyId();
                            accessKeySecret = data.getAccessKeySecret();
                            securityToken = data.getSecurityToken();
                            expiration = data.getExpiration();
                            bucket = data.getBucket();
                            objectKeyPrefix = data.getObjectKeyPrefix();
                            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
                            OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(accessKeyId, accessKeySecret, securityToken);
                            oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);
                            hasSTStoken=true;
                            //upPicture();
                        }
                    }

                    @Override
                    protected void onFailure(Throwable e, boolean isNetWorkError) throws Exception {

                    }

                    @Override
                    protected void onCodeError(OssBean ossBean) throws Exception {
                        super.onCodeError(ossBean);
                        UIUtils.showToast(ApplyRefundActivity.this, ossBean.getErrorMsg(), Toast.LENGTH_SHORT);
                    }
                });
    }

    private void compress(final int i) {
        Log.e("---","进入compress");
        filePath = null;
        if(piclist.get(i).endsWith("jpg") ||piclist.get(i).endsWith("JPG") || piclist.get(i).endsWith("png") ||piclist.get(i).endsWith("PNG") || piclist.get(i).endsWith("JPEG") ||piclist.get(i).endsWith("jpeg")) {
            String IMAGES_PATH = Environment.getExternalStorageDirectory() + "/GJMALL/";
            File imgFile = new File(IMAGES_PATH);
            if (!imgFile.exists()) {
                imgFile.mkdir();
            }
            filePath = IMAGES_PATH+piclist.get(i);
            boolean b = PictureUtils.compressBitmap(mylist.get(i), filePath, 100);
            //压缩成功
            if(b){
                File file = new File(filePath);
                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                android.net.Uri uri = android.net.Uri.fromFile(file);
                intent.setData(uri);
                ApplyRefundActivity.this.sendBroadcast(intent);
                path = filePath;

            }else {//压缩没成功
                path = piclist.get(i);
            }
        }else {//不是jpg或png或jpeg
            path = piclist.get(i);
        }

        PutObjectRequest put =   new PutObjectRequest(bucket, objectKeyPrefix + piclist.get(i), path);
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest putObjectRequest, long l, long l1) {

            }
        });
        oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                successPic++;
                lastUpLoad.add(objectKeyPrefix + piclist.get(i));
                if(successPic==piclist.size()){//所有图片上传成功
                    Log.e("---","isMainThread"+isMainThread());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            commit();
                        }
                    });

                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //清除sd卡缩略图
                        List<String> imagePathFromSD = PictureUtils.getImagePathFromSD();
                        for (int i = 0; i < imagePathFromSD.size(); i++) {
                            File file = new File(imagePathFromSD.get(i));
                            if(file != null) {
                                file.delete();
                                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                                android.net.Uri uri = android.net.Uri.fromFile(file);
                                intent.setData(uri);
                                ApplyRefundActivity.this.sendBroadcast(intent);
                            }
                        }
                    }
                });
            }
            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                UIUtils.showToast(ApplyRefundActivity.this, "上传图片失败", Toast.LENGTH_SHORT);
            }
        });
    }
    public boolean isMainThread() {
        return Looper.getMainLooper() == Looper.myLooper();
    }

    private void commit() {//最后提交
        pics = new String[lastUpLoad.size()];
        lastUpLoad.toArray(pics);
        for (String s : pics) {
            Log.e("---","图片地址:"+s);
        }
        HashMap<String,Object> param=new HashMap<>();
        param.put("reasonId",reasonId);
        param.put("orderId",orderId);
        param.put("orderItemId",orderItemId);
        //param.put("pictures",pics);
        Log.e("---","reasonId="+reasonId+"orderId="+orderId+"orderItemId="+orderItemId);
        RetrofitFactory.getInstant().API()
                .applyService(param)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseEntity>(this,true) {
                    @Override
                    protected void onSuccees(BaseEntity baseEntity) throws Exception {
                        //EventBus.getDefault().postSticky(new RefundScgeduleEventBean("success"));
                        Intent intent=new Intent(ApplyRefundActivity.this,RefundScheduleActivity.class);
                        startActivityForResult(intent,REQUEST_CODE_REFUND);
                    }

                    @Override
                    protected void onFailure(Throwable e, boolean isNetWorkError) throws Exception {
                        if(isNetWorkError) {
                            UIUtils.showToast(ApplyRefundActivity.this, "网络不给力", Toast.LENGTH_SHORT);
                        }else {
                            UIUtils.showToast(ApplyRefundActivity.this, "服务器错误", Toast.LENGTH_SHORT);
                        }
                    }

                    @Override
                    protected void onCodeError(BaseEntity baseEntity) throws Exception {
                        super.onCodeError(baseEntity);
                        UIUtils.showToastShort(ApplyRefundActivity.this,baseEntity.getErrorMsg());
                    }
                });

    }

    private void initPop() {
        LayoutInflater layoutnflater = LayoutInflater.from(this);
        popview = layoutnflater.inflate(R.layout.pop_refundreason_type, null);
        wheelView = (WheelView) popview.findViewById(R.id.wheelview);
        sure = (TextView) popview.findViewById(R.id.tv_confirm);
        leftRl = (RelativeLayout) popview.findViewById(R.id.left_rl);
        rightRl = (RelativeLayout) popview.findViewById(R.id.right_rl);
        wheelView.setData(textlist);
        // int i = list.indexOf(lastString); //记录最后的那个值的下标
        if(index==0){
            index=0;
        }else{
            index = textlist.indexOf(lastString);
        }
        //记录最后的那个值的下标
        if(index== -1){ //如果没有这个下标
            index = CURRENTINDEXT; //还是第一个
        }
        typeName = textlist.get(index);
        wheelView.setDefault(index);

        initPopEvent();
        popwindow = new PopupWindow(popview, LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        popwindow.setBackgroundDrawable(new ColorDrawable(0x80ffffff));
        popwindow.setAnimationStyle(R.style.AnimBottom);
        popwindow.setTouchable(true);
        popwindow.setOutsideTouchable(true);
        popwindow.setFocusable(true);
        popwindow.showAtLocation(reasonRl, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    private void initPopEvent() {
        leftRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WheelView.MOVE_NUMBER = 1;
                wheelView.goonMove(1);
            }
        });

        //右按钮
        rightRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WheelView.MOVE_NUMBER = 1;
                wheelView.goonMove(-1);
            }
        });

        //确定按钮
        sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                reasonTv.setText(typeName);
                popwindow.dismiss();
            }
        });
        wheelView.setOnSelectListener(new WheelView.OnSelectListener() {
            @Override
            public void endSelect(int id, String text) {
                typeName = text;
                lastString = text;
            }
            @Override
            public void selecting(int id, String text) {
            }
        });
    }
    /*public void setText(String text){
        reasonTv.setText(text);
    }*/

    private void select() {
        if (Build.VERSION.SDK_INT >= 23) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(ApplyRefundActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if(checkCallPhonePermission != PackageManager.PERMISSION_GRANTED){
                ActivityCompat.requestPermissions(ApplyRefundActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},REQUEST_READ);
                return;
            }else{
                list=new ArrayList<>();
                startActivityForResult(BGAPhotoPickerActivity.newIntent(this, null,1, list, true), REQUEST_CODE_CHOOSE_PHOTO);
            }
        } else {
            list=new ArrayList<>();
            startActivityForResult(BGAPhotoPickerActivity.newIntent(this, null,1, list, true), REQUEST_CODE_CHOOSE_PHOTO);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case REQUEST_READ:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // Permission Granted
                    list=new ArrayList<>();
                    startActivityForResult(BGAPhotoPickerActivity.newIntent(this, null,1, list, true), REQUEST_CODE_CHOOSE_PHOTO);
                } else {
                    // Permission Denied
                    Toast.makeText(ApplyRefundActivity.this, "权限拒绝", Toast.LENGTH_SHORT)
                            .show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if(requestCode == REQUEST_CODE_COMMIT){
                finish();
            }else if(requestCode == REQUEST_CODE_CHOOSE_PHOTO){
                if(mylist.size()<4){
                    mylist.addAll(BGAPhotoPickerActivity.getSelectedImages(data));
                }else {
                    mylist.set(picIndex,BGAPhotoPickerActivity.getSelectedImages(data).get(0));
                }
                setImage();
            }else if(requestCode==REQUEST_CODE_REFUND){
                finish();
            }
        }
    }

    private void setImage() {
        if(!ListUtils.isEmpty(mylist)){
            switch (mylist.size()){
                case 1:
                    oneIv.setImageBitmap(BitmapFactory.decodeFile(compressPath(mylist.get(0))));
                    break;
                case 2:
                    oneIv.setImageBitmap(BitmapFactory.decodeFile(compressPath(mylist.get(0))));
                    twoIv.setImageBitmap(BitmapFactory.decodeFile(compressPath(mylist.get(1))));
                    break;
                case 3:
                    oneIv.setImageBitmap(BitmapFactory.decodeFile(compressPath(mylist.get(0))));
                    twoIv.setImageBitmap(BitmapFactory.decodeFile(compressPath(mylist.get(1))));
                    threeIv.setImageBitmap(BitmapFactory.decodeFile(compressPath(mylist.get(2))));
                    break;
                case 4:
                    oneIv.setImageBitmap(BitmapFactory.decodeFile(compressPath(mylist.get(0))));
                    twoIv.setImageBitmap(BitmapFactory.decodeFile(compressPath(mylist.get(1))));
                    threeIv.setImageBitmap(BitmapFactory.decodeFile(compressPath(mylist.get(2))));
                    fourIv.setImageBitmap(BitmapFactory.decodeFile(compressPath(mylist.get(3))));
                    break;
                default:
                    break;
            }

        }
    }
    public String  compressPath(String path ){
        if(path.endsWith("jpg") ||path.endsWith("JPG") ||path.endsWith("png") ||path.endsWith("PNG") || path.endsWith("JPEG") ||path.endsWith("jpeg")) {
            String IMAGES_PATH = Environment.getExternalStorageDirectory() + "/GJMALL/";
            File imgFile = new File(IMAGES_PATH);
            if (!imgFile.exists()) {
                imgFile.mkdir();
            }
            int start = path.lastIndexOf("/");
            String filename = path.substring(start + 1, path.length());
            filePath = IMAGES_PATH+filename;
            boolean b = PictureUtils.compressBitmap(path, filePath, 100);
            //压缩成功
            if(b){
                File file = new File(filePath);
                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                android.net.Uri uri = android.net.Uri.fromFile(file);
                intent.setData(uri);
                ApplyRefundActivity.this.sendBroadcast(intent);
                return filePath;
            }else {//压缩没成功
                return path;
            }
        }else {//不是jpg或png或jpeg
            return path;
        }
    }
}
